# -*- coding: utf-8 -*-
"""
配置管理器
负责程序配置的读取、保存和管理
"""

import os
import json
from typing import Dict, Any, Optional


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_file: str = "config.json"):
        """初始化配置管理器"""
        self.config_file = os.path.join(
            os.path.dirname(os.path.dirname(__file__)), 
            config_file
        )
        self.config: Dict[str, Any] = {}
        self.default_config = {
            "version": "1.0.0",
            "language": "zh_CN",
            "auto_save": True,
            "plugin_auto_load": True,
            "log_level": "INFO",
            "theme": "default",
            "plugins": {
                "enabled": [],
                "disabled": []
            }
        }
        
        self.load_config()
        
    def load_config(self):
        """加载配置文件"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    self.config = json.load(f)
                    
                # 合并默认配置（确保新增的配置项存在）
                self._merge_default_config()
            else:
                # 如果配置文件不存在，使用默认配置
                self.config = self.default_config.copy()
                self.save_config()
                
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            print("使用默认配置")
            self.config = self.default_config.copy()
            
    def save_config(self):
        """保存配置文件"""
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
                
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            
    def get_config(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        keys = key.split('.')
        value = self.config
        
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
            
    def set_config(self, key: str, value: Any):
        """设置配置项"""
        keys = key.split('.')
        config = self.config
        
        # 导航到最后一级的父级
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
            
        # 设置值
        config[keys[-1]] = value
        
        # 自动保存
        if self.get_config('auto_save', True):
            self.save_config()
            
    def get_all_config(self) -> Dict[str, Any]:
        """获取所有配置"""
        return self.config.copy()
        
    def reset_config(self):
        """重置配置为默认值"""
        self.config = self.default_config.copy()
        self.save_config()
        
    def _merge_default_config(self):
        """合并默认配置"""
        def merge_dict(target: dict, source: dict):
            for key, value in source.items():
                if key not in target:
                    target[key] = value
                elif isinstance(value, dict) and isinstance(target[key], dict):
                    merge_dict(target[key], value)
                    
        merge_dict(self.config, self.default_config)
        
    def is_plugin_enabled(self, plugin_name: str) -> bool:
        """检查插件是否启用"""
        enabled_plugins = self.get_config('plugins.enabled', [])
        disabled_plugins = self.get_config('plugins.disabled', [])
        
        if plugin_name in disabled_plugins:
            return False
        if plugin_name in enabled_plugins:
            return True
            
        # 默认启用
        return True
        
    def enable_plugin(self, plugin_name: str):
        """启用插件"""
        enabled = self.get_config('plugins.enabled', [])
        disabled = self.get_config('plugins.disabled', [])
        
        if plugin_name not in enabled:
            enabled.append(plugin_name)
            
        if plugin_name in disabled:
            disabled.remove(plugin_name)
            
        self.set_config('plugins.enabled', enabled)
        self.set_config('plugins.disabled', disabled)
        
    def disable_plugin(self, plugin_name: str):
        """禁用插件"""
        enabled = self.get_config('plugins.enabled', [])
        disabled = self.get_config('plugins.disabled', [])
        
        if plugin_name in enabled:
            enabled.remove(plugin_name)
            
        if plugin_name not in disabled:
            disabled.append(plugin_name)
            
        self.set_config('plugins.enabled', enabled)
        self.set_config('plugins.disabled', disabled)